package com.apkplug.osgi.activity;
import com.apkplug.osgi.service.*;
import com.apkplug.osgi.serviceImp.showViewImp;
import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
import org.osgi.framework.InvalidSyntaxException;
import org.osgi.framework.ServiceEvent;
import org.osgi.framework.ServiceListener;
import org.osgi.framework.ServiceReference;
import org.osgi.framework.ServiceRegistration;
public class ViewActivator implements BundleActivator{
	private ServiceRegistration m_reg = null;
	private showView showView=null;
	private ServiceReference ref=null;
	private printLog service=null;
	//打印日志服务使用前需先判断
	public printLog getService() {
		return service;
	}
	public ViewActivator(showView showView){
		this.showView=showView;
	}
	@Override
	public void start(final BundleContext context) {
		//注册一个服务给插件调用
		m_reg = context.registerService(
				showView.class.getName(),
				showView,
	            null);
		
			try {
				context.addServiceListener(
						new ServiceListener(){
							@Override
							public void serviceChanged(ServiceEvent event) {
								switch  (event.getType()) {
									case  ServiceEvent.REGISTERED:
										if  (ref  ==   null ) {
											ref  =  event.getServiceReference();
											service  =  (printLog) context.getService(ref);//保存实例以备后续访问
											
										}
										break ;
									case  ServiceEvent.UNREGISTERING:
										if  (ref  ==  event.getServiceReference()) {
											context.ungetService(ref); //释放实例 
												service  =   null ;
												ref  =   null ;
										}
										break ;
									}
								
							}
				},"(objectclass=com.apkplug.osgi.service.printLog)" );
			} catch (InvalidSyntaxException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
	}
	@Override
	public void stop(BundleContext arg0) {
		m_reg.unregister();
	}
}
